#ifndef ANALYSIS_MODBUS_H
#define ANALYSIS_MODBUS_H
#include<QByteArray>
#include<QObject>
#include<QDebug>
#include<QSettings>
#include<QThread>
#include"./utils/commont.h"
#include"./utils/crc.h"
using namespace JQChecksum;
/******************宏定义*******************/
//数据长度
#define MAXDATA                256
#define ADDRESS_MAX            65535
//MODBUS协议标识符
#define MB_PROTOCOL            0x0000
//读取的线圈寄存器功能码     01
#define READER_COIL_CODE       0x01
//读保持寄存器功能码        03
#define Read_REGISTER          0x03
//写线圈寄存器功能码        0f
#define WRITE_COIL             0x0f
//写保持寄存器功能码        10
#define WRITE_REGISTER         0x10
#define CRC_FLAG 0
typedef enum RTU_MODBUS_STATE
{
    //功能码错误
   MB_SLAVE_STATE_FUNCTION_ERROR = 1,
    //数据值错误
   MB_SLAVE_STATE_DATA_ERROR = 2,
    //数据地址错误
   MB_SLAVE_STATE_DATAADDR_ERROR = 3,
    //从机地址
   MB_SLAVE_STATE__ADDR_ERROR = 4,
    //正确帧
   MB_SLAVE_STATE_PACKET_PROCESS = 5,
    //其他
   MB_SLAVE_STATE_PACKET_OTHER = 6,
}MB_satae;

class analysis_modbus : public QObject
{
    Q_OBJECT
public:
    explicit analysis_modbus();
    ~analysis_modbus();
    //状态处理
    void parse_Modbus_MB_satae(MB_satae);
    //正常帧处理
    void parse_Modbus_True_Msg(QByteArray msg);
    //异常处理
    void parse_Modbus_Exception_Handling03();
    void parse_Modbus_Exception_Handling02();
    void parse_Modbus_Exception_Handling01();
    //解析报文查询状态
    MB_satae parse_Modbus_Msg(QByteArray msg);
    //报文数据读取提示
    void ReadCoilPackMsgToShow(quint16 startaddr,quint16 num,QByteArray msg);
    void ReadRegsPackMsgToShow(quint16 startaddr,quint16 num,QVector<quint16> msg);
    //报文写入提示
    void WirteCoilPackMsgToShow(quint16 startaddr,quint16 num,QByteArray msg);
    void WirteRegsPackMsgToShow(quint16 startaddr,quint16 num,QVector<quint16> msg);
    //功能码处理函数
    void func_01();
    void func_03();
    void func_0f();
    void func_10();


signals:
    //解析完成
    void analysis_over(QByteArray ba);
    void wirtTablec(quint16 num, quint16 satrtaddr,QString bac);
    void wirtTabler(quint16 num, quint16 satrtaddr,QVector<quint16> bar);
    void toUishowMsg(QString errorMsg);
    void toUishowMsgPack(QByteArray packMsg);
public slots:
    //接收报文
    MB_satae recvModbusMsg(QByteArray msg);
    //封装ini线圈状态to byte
    void GetData0X01(QByteArray &ba,quint16 BeginAddress,quint16 Number);
    //封装字节数据to ini线圈状态
    QString HexByteArrayToBinString(QByteArray DataArray);
    void WriteData0X0F(quint16 satrt,QString CoilData);
private:
    QByteArray recvModbusmsg;
    QByteArray sendModbusmsg;
    QByteArray testsendModbusmsg;
    quint16 mb_startaddr,mb_num;
    quint16 mb_code;
    quint8  mb_addr=1;
    QThread *m_thread;
    quint16 wnum;
    QSettings* readseting=nullptr;
    QVector<quint16> bar;
    QVector<quint16> msg;
    QString bac;
    QString errorMsg;
};
#endif // ANALYSIS_MODBUS_H
